package com.bolang.onlycode.demo.Cache;

import sun.misc.Unsafe;

import java.util.Map;
import java.util.concurrent.*;

public class Memorizer4<A,V>implements Computable<A,V> {
    // 得有个容器来放缓存
    private final Map<A,Future<V>> cache =new ConcurrentHashMap<A,Future<V>>();
    // 得有计算功能
    private final Computable<A,V> c;
    public Memorizer4(Computable<A,V> c){
        this.c=c;
    }
    @Override
    public V compute(A arg) throws InterruptedException {
        while (true){
            Future<V> f = cache.get(arg);
            if (f == null) {
                Callable<V> eval = new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return c.compute(arg);
                    }
                };
                FutureTask<V> ft = new FutureTask<V>(eval);
                f =cache.putIfAbsent(arg,ft);
                if(f==null){
                    f=ft;
                    ft.run();
                }
            }
            try {
                return f.get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
